package com.qs.springboot.amqp.simple;

import com.qs.springboot.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 测试：消费方可以手动进行ack，对接收到的消息进行确认，避免因为异常，造成消息丢失。
 */
public class Receive2 {

    private static final String QUEUE_NAME = "simple_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("--->>接收的消息：" + msg);

                //手动进行ack
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        //监听队列，第二个参数false，手动进行ack
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }

}
